package ru.ifmo.swing.genetics.termination;

import org.uncommons.watchmaker.framework.PopulationData;
import org.uncommons.watchmaker.framework.TerminationCondition;
import org.uncommons.watchmaker.swing.EvolutionControl;
import ru.ifmo.automaton.Automaton;
import ru.ifmo.automaton.SynchronizingAutomaton;
import ru.ifmo.common.Source;
import ru.ifmo.genetics.automaton.synchronizeable.fitness.StandartFitness;
import ru.ifmo.swing.Panel;

import javax.swing.*;

/**
 * @author Roman Kolganov
 *         16.05.12
 */
public class MSWFoundCondition implements EvolutionControl, TerminationCondition {

    private final Panel control = new Panel();
    private final Source<Automaton<Character, String>> automatonSource;

    public MSWFoundCondition(Source<Automaton<Character, String>> automatonSource) {
        this.automatonSource = automatonSource;
    }

    public JComponent getControl() {
        return control;
    }

    public void reset() {
    }

    public void setDescription(String description) {
        control.setTitle(description);
    }

    public boolean shouldTerminate(PopulationData<?> populationData) {
        String bestIndividual = (String) populationData.getBestCandidate();
        Automaton<Character, String> a = automatonSource.create();
        if (a instanceof SynchronizingAutomaton) {
            SynchronizingAutomaton<Character, String> automaton =
                    (SynchronizingAutomaton<Character, String>) automatonSource.create();
            return automaton.getStatesCount() - StandartFitness.df(automaton, bestIndividual) == 1 &&
                    bestIndividual.length() == automaton.mswLength();
        } else {
            return false;
        }
    }
}
